<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-menu"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="addForm" :rules="rules" ref="addForm">
                    <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                        <el-input v-model="addForm.username" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password" :label-width="formLabelWidth">
                        <el-input v-model="addForm.password" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户角色" prop="roleId" :label-width="formLabelWidth">
                        <el-select v-model="addForm.roleId" placeholder="请选择用户角色" @change="roleChange">
                            <el-option v-for="role in roles" :key="role.id" :label="role.role_name" :value="role.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="roleType === 'allianceManager'" label="选择机构" prop="organization_id" :label-width="formLabelWidth">
                        <el-select v-model="addForm.organizationId" placeholder="请选择机构" @change="orgChange">
                            <el-option v-for="org in allOrgs" :key="org.id" :label="org.name" :value="org.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </div>
            </el-dialog>
            <el-input v-model="select_word" placeholder="输入用户名" class="search"></el-input>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button type="primary" @click="beforeAdd">新增用户</el-button>
        </div>
        <div>
            <el-table :data="tableData" border fit style="width: 100%">
                <el-table-column prop="user_name" label="姓名"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column prop="user_pwd_mw" label="密码"></el-table-column>
                <el-table-column prop="organization_id" label="机构" :formatter="orgFor"></el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button type="text" size="small" @click="delUser(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="block">
            <el-pagination @current-change="handleCurrentChange" :current-page="page.number" 
            layout="total, prev, pager, next, jumper" :total="page.total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import { users, delUser, addUser, putUser, add_user, 
getAllRoles, user, org } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
import { confirm, dateFormatter, getStore } from '../../utils/local'
const { updateUser } = user 
const { allOrg } = org
export default {
    data() {
        return {
            title: '新增角色',
            value: '',
            loading: false,
            dialogTableVisible: false,
            dialogFormVisible: false,
            dialogFormUpdate: false,
            select_word: '',
            addForm: {
                organizationId: ''
            },
            allOrgs: [],
            roleType: '',
            rules: {
                username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
                organizationId: [{ required: true, message: '请选择机构', trigger: 'blur' }],
            },
            formLabelWidth: '120px'
        }
    },
    created() {
        this.getUsers(1)
        this.getRoles()
        this.getOrgs()
    },
    computed: mapState({
        page: state => state.Users.page,
        tableData: state => state.Users.result,
        roles: state => state.Users.roles,
    }),
    methods: {
        ...mapActions(['saveUsers', 'saveRoles']),
        getUsers(number) {
            const params = {
                page: number,
                pageSize: 10
            }
            if (this.select_word !== '') {
                params.searchKey = this.select_word
            }
            users({ ...params }).then(res => {
                if (res.code === '000000') {
                    this.saveUsers({
                        ...res,
                        number
                    })
                }
            })
        },
        getOrgs() {
            allOrg().then(res => {
                if (res.code === '000000') {
                    this.allOrgs = res.result
                } else {
                    this.$message.error(res.message)
                }
            }, () => this.$message.error('网络错误'))
        },
        dateFormatter(row, column) {
             return  dateFormatter(row.update_at)
        },
        orgFor(row) {
            let orgName = ''
            this.allOrgs.some(item => {
                if (item.id === row.organization_id) {
                    orgName = item.name
                    return true
                }
            })
            return orgName
        },
        search() {
           this.getUsers(this.page.number)
        },
        handleCurrentChange(val) {
            this.getUsers(val)
        },
        delUser(row) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let id = row.id
                delUser({ userId: id })
                    .then(res => {
                        if (res.code === '000000') {
                            this.getUsers(this.page.number)
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        add() {
            if (this.addForm.id) {
                this.putUser()
            } else {
                const userEntity = {
                    userName: this.addForm.username,
                    userPwd: this.addForm.password,
                    userRoleId: this.addForm.roleId,
                }
                if (this.addForm.organization_id) {
                    userEntity.organizationId = this.addForm.organization_id
                }
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        addUser({ ...userEntity })
                            .then(res => {
                                if (res.code === '000000') {
                                    this.dialogFormVisible = false
                                    this.$message.success("添加成功")
                                    this.getUsers(this.page.number) //重新查找列表数据
                                } else {
                                    this.$message.error(res.message)
                                }
                            })
                    }
                })
            }
        },
        // 新增用户
        beforeAdd() {
            this.dialogFormVisible = true
            this.addForm = {}
            this.roleType = ''
        },
        getRoles() {
            //查询所有用户角色
            getAllRoles({ page: 1, pageSize: 100000 }).then(res => {
                if (res.code === '000000') {
                    this.saveRoles(res)
                }
            })
        },
        roleChange: function(value) {
            this.roles.some(item => {
                if (item.id === value) {
                    this.roleType = item.role_type
                    return true
                }
            })
        },
        orgChange(value) {
            console.log(this.addForm.organizationId, value)
            this.addForm.organizationId = value
        },
        edit(row) {
            this.dialogFormVisible = true
            this.title = '编辑角色'
            this.addForm.username = row.user_name
            this.addForm.password = row.user_pwd_mw
            this.addForm.roleId = row.role_id
            this.addForm.id = row.id
            this.roles.some(item => {
                if (item.id === row.role_id) {
                    this.roleType = item.role_type
                    return true
                }
            })
            this.addForm.organizationId = row.organization_id
        },
        putUser() {
            const userEntity = {
                userId: this.addForm.id,
                userName: this.addForm.username,
                userPwd: this.addForm.password,
                roleId: this.addForm.roleId,
            }
            if (this.addForm.organizationId) {
                userEntity.organizationId = this.addForm.organizationId
            }
            updateUser({ ...userEntity })
                .then(res => {
                    if (res.code === '000000') {
                        this.dialogFormVisible = false
                        this.getUsers(this.page.number)
                    } else {
                        this.$message.error(res.message)
                    }
                }, err => this.$message.error(res.message))
        },
    }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
</style>
